package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//权限拦截器
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    //访问拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求request当中调用getSession()得到session
        HttpSession session = request.getSession();
        //再用session调用getAttribute得到session的value
        Employee attribute = (Employee) session.getAttribute(Constant.SESSION_EMPLOYEE);
        //如果未登录
        if(attribute == null){
            // 拦截，返回错误信息
            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
            // 将结果转换json
            String s = JSON.toJSONString(resultInfo);
            response.getWriter().write(s);
            return false;
        }
        EmployeeHolder.set(attribute);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        EmployeeHolder.remove();
    }
}
